package com.slfx.idgen.demo.idgen.snowflake;


import com.slfx.idgen.demo.idgen.exception.GenIdException;
import com.slfx.idgen.demo.idgen.utils.IpAddressUtil;
import com.slfx.idgen.demo.idgen.utils.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class SnowflakeIdWorkerClient implements IdWorker {

    private Logger logger = LoggerFactory.getLogger(SnowflakeIdWorkerClient.class);

    private String appName;

    private int port;

    @Autowired(required = false)
    private LoadBalancerClient loadBalancerClient;

    public SnowflakeIdWorkerClient(String appName, int port) {
        this.appName = appName;
        this.port = port;
    }

    @Override
    public long initWorkerId() {
//        final String LOCATION = "/workerId?appName=" + appName + "&&ip=" + IpAddressUtil.getIp() + "&&port="+port;
//        final String SERVICE_ID = "LOGISTICS-IDGEN-SERVER";
//
//        final String successCode = "0";
//
//        ServiceInstance idgenInstance = loadBalancerClient.choose(SERVICE_ID);
//
//        if (idgenInstance == null || idgenInstance.getUri() == null) {
//            logger.error("没有找到id生成服务端:{}", SERVICE_ID);
//            throw new GenIdException("初始化workerId出错,没有找到id生成服务端..");
//        }
//
//        RestTemplate restTemplate = new RestTemplate();
//
//        ResponseEntity<JsonResponse<Worker>> responseEntity = restTemplate.exchange(idgenInstance.getUri() + LOCATION, HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<JsonResponse<Worker>>() {
//        });
//        JsonResponse<Worker> body = responseEntity.getBody();
//
//        if (!successCode.equals(body.getCode())) {
//            throw new GenIdException(responseEntity.getBody().getMsg());
//        }
//
//
//        if ( body.getData() == null) {
//
//            throw new GenIdException("获取workerId错误");
//
//        }
//
//        Worker worker = body.getData();
//
//        return worker.getWorkerId();
        return 1L;

    }


}
